﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Rotas.aspx.cs" Inherits="EasyFrota_Mobile.Rotas" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<%-- <style>   #popupPanel-popup {
    right: 0 !important;
    left: auto !important;
}
#popupPanel {
   
    border: 2px solid #000000;
    border-right: none;
    background: rgba(1,1,1,0.5);
    margin: -1px 0;
    color: #FFFFFF;
}
#popupPanel .ui-btn {
    margin: 2em 15px;
}

</style>--%>
    <asp:HiddenField ID="HiddenField1" runat="server" />
    <asp:DropDownList ID="dropDownRota" runat="server" data-native-menu="false" 
        onselectedindexchanged="dropDownRota_SelectedIndexChanged" AutoPostBack="True">
    </asp:DropDownList>
    <asp:DropDownList ID="dropDownVeiculos" runat="server" data-native-menu="false" 
        onselectedindexchanged="dropDownVeiculos_SelectedIndexChanged" AutoPostBack="True">
    </asp:DropDownList>
  <%--  <input id="Button1" type="button" value="Ver Rota" onclick="marcas();" />--%>
     
    
    <div data-role="popup" id="popupPanel" data-position-to="window" data-corners="true" data-overlay-theme="a" data-theme="a" data-shadow="true" data-tolerance="15,15">

     <br/>
                 <h3>Formulário</h3>
                   
                <a href="#" data-rel="back" data-role="button" data-theme="a" data-icon="delete" data-iconpos="notext" class="ui-btn-right">Close</a>
    <div data-role="fieldcontain" data-mini="true">
    
    <input type="text" data-mini="true" name="name" data-inline="true" placeholder="Funcionario" id="funcionario" value=""/>
    

    </div>	
       <asp:DropDownList ID="DropDownHora" data-mini="false" runat="server" data-native-menu="false" data-inline="true" data-dismissable="true">
        </asp:DropDownList>
    
    <asp:DropDownList ID="DropDownMinuto" data-placeholder="true" data-mini="false" runat="server" data-inline="true" data-native-menu="false">
        </asp:DropDownList>
	<%-- <label for="slider-1">Hora:</label>
<input type="range" data-mini="true" name="slider-1" id="Hora" value="Hora" min="0" max="23" />
	 <label for="slider-1">Minuto:</label>
<input type="range" data-mini="true" name="slider-1" id="Minuto" value="Minuto" min="0" max="59" />--%>
 <input id="Button3" data-mini="true" data-inline="true" data-icon="check" type="button" value="Inserir" onclick="teste();"/>
</div>

    <div data-role="popup" id="popupPanelErro" data-position-to="window" data-corners="true" data-overlay-theme="a" data-theme="a" data-shadow="true" data-tolerance="15,15">

     <br/>
                 <h3>Erro</h3>
                   
                <a href="#" data-rel="back" data-role="button" data-theme="a" data-icon="delete" data-iconpos="notext" class="ui-btn-right">Close</a>
    
</div>

   
     <div id="map_canvas" style="width: 100%; height: 400px;"></div>
     
     <script type="text/javascript">
         /*
         IDRota", rotas[i].Rota.IDRota.ToString() }, 
                                        { "Morada", rotas[i].Morada.ToString() },
                                        { "Label", rotas[i].Label.ToString() },
                                         { "Longitude", rotas[i].Longitude.ToString().Replace(',','.') },
                                          { "Latitude", rotas[i].Latitude.ToString().Replace(',','.') },
                                              { "Ordem", rotas[i].Ordem.ToString()},
                                              {"DataInsercao",rotas[i].DataInsercao.ToString()},
                                              {"NomeRota",rotas[i].Rota.Nome.ToString()},
                                              {"RotaMarca",rotas[i].IDRotaMarca.ToString()},
         */
         var marcadores = [];
         var lat;
         var lng;
         var geocoder;
         var point = 0;
         var idMarca;
         var nomeRota;
         var Ordem;
         var Morada;
         var Label;
         var rota=[];
         var idCarro;
         var info = [];
         var percurso = [];
         var latitudeVeiculo;
         var longitudeVeiculo;
         
         var idMarcaActual;

         function initialize() {
            
             geocoder = new google.maps.Geocoder();
             var portugal = new google.maps.LatLng(39.6037, -8.41379);
             point = "0";
             var myOptions = {
                 zoom: 6,
                 mapTypeId: google.maps.MapTypeId.ROADMAP,
                 streetViewControl: false,
                 scaleControl: false,
                 scrollwheel: true,
                 center: portugal
             };
             map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            // var now = new Date();
           //  var today = now.getDate() + '/' + (now.getMonth() + 1) + '/' + now.getFullYear();
            //alert(today);
           //  document.getElementById('date').value = today;
             marcas();
         }

         function marcas() {
      
             var rota = document.getElementById('<%=dropDownRota.ClientID%>');
             var idRota = rota.options[rota.selectedIndex].value;
             var carro = document.getElementById('<%=dropDownVeiculos.ClientID%>');
           
             idCarro = carro.options[carro.selectedIndex].value;
             // alert(idRota);
             //  alert(idCarro);
             LocalizaVeiculo(idCarro);
             getPercurso(idCarro, idRota);
             AdicionarMarcadores(idRota);
             EscreverRotaMapa(idRota);
         };
         function AdicionarMarcadores(idRota) {
               
             //   alert(flag);
             $.ajax({
                 type: "POST",
                 contentType: "application/json; charset=utf-8",
                 url: "Servicos/ServicoRotas.asmx/GetRotaMarcas",
                 data: "{ idRota: " + idRota + "}",
                 dataType: "json",
                 async: false,
                 success: function (response) {
                     var tam = response.d.length;
                     //    alert(tam);
                     for (var i = 0; i < tam; i++) {
                         Morada = response.d[i].Morada;
                         Label = response.d[i].Label;
                         Ordem = response.d[i].Ordem;
                         lat = response.d[i].Latitude;
                         lng = response.d[i].Longitude;
                         nomeRota = response.d[i].NomeRota;
                         idMarca = response.d[i].RotaMarca;
                         //alert(nomeRota);
                         PutMarkerOnMap(lat, lng, Ordem, Label, Morada, nomeRota, i, idMarca);
                     }

                     // CriarMarcador(idActual, matricula, tipo, lat, lng, lig);
                 },
                 error: function (request, status, error) {
                 }
             });
         };

         function PutMarkerOnMap(lat, lng, Ordem, Label, Morada, nomeRota, i, idMarca) {
             var number = new google.maps.MarkerImage();
         
             number.url = "images/numbers/black" + (i + 1) + ".png";
         
             number.size = new google.maps.Size(32, 32);
             number.anchor = new google.maps.Point(16, 16);
             var point = new google.maps.LatLng(lat, lng);
             var desc = nomeRota;
             var shadow = new google.maps.MarkerImage('images/caricon_shadow.png', new google.maps.Size(42, 18), new google.maps.Point(0, 0), new google.maps.Point(16, 16));
             var marker = new google.maps.Marker({
                 position: point,
                 icon:number,
                 clickable: true,
                 title: desc,
                 shadow:shadow,
                 draggable: false,
                 map: map
             });

             marcadores[i] = marker;
             marcadores[i] = google.maps.event.addListener(marker, 'click', function () {
                 infowindow = new google.maps.InfoWindow({


                     content: "Descrição: " + Label + "<br/> Morada:" + Morada + "<br/><p></p>" +

                         "<a href=#popupPanel data-rel=popup data-transition=slide data-position-to=window data-role=button><input type=button value='Efectuar entrega'/></a>"
                    
                 });
                 idMarcaActual = idMarca;
                 // alert(idMarcaActual);
                 // $.mobile.pushStateEnabled = false;
                 infowindow.open(map, marker);
             });
         };
     
         function EscreverRotaMapa(idRota) {

             $.ajax({
                 type: "POST",
                 contentType: "application/json; charset=utf-8",
                 url: "Servicos/ServicoRotas.asmx/GetRotaId",
                 data: "{ idRota: " + idRota + "}",
                 dataType: "json",
                 async: false,
                 success: function (response) {
                     var tam = response.d.length;
                     //  alert(tam);
                     for (var i = 0; i < tam; i++) {
                         rota.push(new google.maps.LatLng(response.d[i].Latitude, response.d[i].Longitude));
                     }
                       
                 },
                 error: function (request, status, error) {
                 }
             });



             /*                var flightPlanCoordinates = [];

                  flightPlanCoordinates.push(new google.maps.LatLng(37.772323, -122.214897));
                  flightPlanCoordinates.push(new google.maps.LatLng(21.291982, -157.821856));
                  flightPlanCoordinates.push(new google.maps.LatLng(21.291982, -157.821856));
                  */
             var routePath = new google.maps.Polyline({
                 path: rota,
                 strokeColor: '#0000FF',
                 strokeOpacity: 1.0,
                 strokeWeight: 7
             });
             routePath.setMap(map);
         };

         //LOCALIZAR VEICULO ASSOCIADO   

         function LocalizaVeiculo(idCarro) {

             $.ajax({
                 type: "POST",
                 contentType: "application/json; charset=utf-8",
                 url: "Servicos/localveiculo.asmx/ObterCoordenadasDaLocalidade",
                 data: "{ IdViatura: " + idCarro + "}",
                 dataType: "json",
                 async: false,
                 success: function (response) {
                     // var id = response.d[0].IdViatura;
                     var matricula = response.d[0].Matricula;
                     var tipo = response.d[0].TipoViatura;
                     latitudeVeiculo = response.d[0].Latitude;
                     longitudeVeiculo= response.d[0].Longitude;
                     var lig = response.d[0].Ligado;
                     // alert(id);
                     // alert(matricula);
                     // alert(tipo);
                     // alert(lat);
                     // alert(lng);
                     CriarMarcador(idCarro, matricula, tipo, latitudeVeiculo, longitudeVeiculo, lig);
                 },
                 error: function (request, status, error) {
                 }
             });


         };

         function CriarMarcador(idActual, matricula, tipoVia, latitudeVeiculo, longitudeVeiculo, lig) {

             var point = new google.maps.LatLng(latitudeVeiculo, longitudeVeiculo);
             var car = new google.maps.MarkerImage();

             if (tipoVia == "Ligeiro" || tipoVia == "Misto") {
                 if (lig == "Não") {
                     car.url = "images/cars/carofficon-0.png";
                 }
                 else {
                     car.url = "images/cars/caricon-0.png";
                 }

                 car.size = new google.maps.Size(32, 32);
                 car.anchor = new google.maps.Point(16, 16);
             }

             if (tipoVia == "Grua") {
                 if (lig == "Não") {
                     car.url = "Images/Cars/gruaofficon-0.png";
                 } else {
                     car.url = "Images/Cars/gruaicon-0.png";
                 }
                 car.size = new google.maps.Size(32, 32);
                 car.anchor = new google.maps.Point(16, 16);
             }

             if (tipoVia == "Pesado") {
                 if (lig == "Não") {
                     car.url = "Images/Cars/camiaoofficon-0.png";
                 } else {
                     car.url = "Images/Cars/camiaoicon-0.png";
                 }
                 car.size = new google.maps.Size(32, 32);
                 car.anchor = new google.maps.Point(16, 16);
             }


             var desc = tipoVia;
             var shadow = new google.maps.MarkerImage('images/caricon_shadow.png', new google.maps.Size(42, 18), new google.maps.Point(0, 0), new google.maps.Point(16, 16));
             var marker = new google.maps.Marker({
                 position: point,
                 icon: car,
                 shadow: shadow,
                 clickable: true,
                 title: desc,
                 draggable: true,
                 map: map
             });

             //associativo[idActual] = marker;
             info[idCarro] = google.maps.event.addListener(marker, 'click', function () {

                 if (tipoVia != "Grua") {


                     //jQuery.mobile.changePage($("#dia", { role: "dialog" }));
                     infowindow = new google.maps.InfoWindow({
                         content: "Matricula: " + matricula + "<br/> Categoria:" + tipoVia + "<br/>" + "Ligado:" + lig
                     });
                 } else {

                     infowindow = new google.maps.InfoWindow({
                         content: "Categoria: " + matricula
                     });

                 }

                 infowindow.open(map, marker);

             });

             info[idActual] = google.maps.event.addListener(marker, "drag", function () {
                 // Add a alert: Are you sure you want to remove this marker?

                 marker.setMap(null);

             });


         };
         //Escrever Percurso do veiculo associado à rota naquele espaço de tempo

         function getPercurso(idCarro, idRota) {

             $.ajax({
                 type: "POST",
                 contentType: "application/json; charset=utf-8",
                 url: "Servicos/ServicoRotas.asmx/getPercursoVeiculo",
                 data: "{idCarro:"+idCarro+", idRota: " + idRota + "}",
                 dataType: "json",
                 async: false,
                 success: function (response) {
                     var tam = response.d.length;
                     //    alert(tam);
                     for (var i = 0; i < tam; i++) {
                         percurso.push(new google.maps.LatLng(response.d[i].Latitude, response.d[i].Longitude));
                              
                     }

                     // CriarMarcador(idActual, matricula, tipo, lat, lng, lig);
                 },
                 error: function (request, status, error) {
                 }
             });

             var percursoEscrever = new google.maps.Polyline({
                 path: percurso,
                 strokeColor: '#FF0000',
                 strokeOpacity: 1.0,
                 strokeWeight: 7
             });
             percursoEscrever.setMap(map);

         };

         function teste() {
            // window.location = "#popupPanelErro";
            // alert(idMarcaActual);
            var funcionario = document.getElementById('funcionario').value;
            var idRotaViatura=(document.getElementById('MainContent_HiddenField1').value);
          //  alert(idRotaViatura);

            var hora = document.getElementById('<%=DropDownHora.ClientID%>');
            var h = hora.options[hora.selectedIndex].value;

            var minuto = document.getElementById('<%=DropDownMinuto.ClientID%>');
            var m = minuto.options[minuto.selectedIndex].value;
         //    alert(m);
       //     alert(h);
            //      alert(funcionario);

          
             $.ajax({
                 type: "POST",
                 contentType: "application/json; charset=utf-8",
                 url: "Servicos/ServicoRotas.asmx/insertEntregaMarca",
                 data: "{idMarcaActual:" + idMarcaActual + ", idRotaViatura: " + idRotaViatura + ", funcionario:'" + funcionario + "', h:" + h + ",m:" + m + "}",
                 dataType: "json",
                 async: false,
                 success: function (response) {
                    // alert(response.d.success);
                     alert(response.d.message);
                     // CriarMarcador(idActual, matricula, tipo, lat, lng, lig);
                 },
                 error: function (request, status, error) {
                 }
             });

           
             history.back();
             initialize();

         }
     </script>
</asp:Content>
